package com.itisyue.fun.utils;

import org.yaml.snakeyaml.Yaml;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
 
/**
 * @Title:
 * @Description:  yml转properties工具

<dependency>
    <groupId>org.yaml</groupId>
    <artifactId>snakeyaml</artifactId>
    <version>1.29</version>
</dependency>
 */
public class YmlToPropertiesUtil {
 
    public static void main(String[] args) {
        String path = "D:\\develop\\workspace_idea\\my-java\\tools-tech\\src\\main\\resources\\application.yml";
        printProperties(path);
    }

    public static void printProperties(String path){
        LinkedHashMap<String, Object> result = ymlToProperties(path);
        Iterator<Map.Entry<String, Object>> iterator = result.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, Object> next = iterator.next();
            System.out.println(next.getKey() + "=" + next.getValue());
        }
    }

    private static LinkedHashMap<String, Object> ymlToProperties(String path) {
        LinkedHashMap<String, Object> resultMap = null;
        Yaml yaml = new Yaml();
        FileInputStream in = null;
        try {
            in = new FileInputStream(path);
            LinkedHashMap<String, Object> m = yaml.load(in);
            resultMap = mapToPorperties(m);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return resultMap;
    }

    private static LinkedHashMap<String, Object> mapToPorperties(LinkedHashMap<String, Object> m) {
        final LinkedHashMap<String, Object> resultMap = new LinkedHashMap<>();
        mapToPorperties(null, resultMap, m);
        return resultMap;
    }
 
    private static void mapToPorperties(String key, final LinkedHashMap<String, Object> toMap, LinkedHashMap<String, Object> fromMap) {
        Iterator<Map.Entry<String, Object>> it = fromMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = it.next();
            Object value = entry.getValue();
            if (value instanceof Map) {
                String relKey = entry.getKey();
                if (key != null) {
                    relKey = key + "." + entry.getKey();
                }
                mapToPorperties(relKey, toMap, (LinkedHashMap<String, Object>) value);
            } else {
                String relKey = entry.getKey();
                if (key != null) {
                    relKey = key + "." + entry.getKey();
                }
                toMap.put(relKey, entry.getValue());
            }
        }
    }
 
}